/* 
 *  Copyright (c) 2012 Shirou Maruyama
 * 
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 * 
 *   1. Redistributions of source code must retain the above Copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above Copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 */

#include <string>
#include <fstream>
#include <algorithm>
#include <stdint.h>
#include "pacbeep.hpp"
#include "slp2txt.hpp"
#include "cmdline.h"

#include <time.h>
#include <sys/time.h>
#include <stdio.h>

using namespace std;
using namespace pacbeep;

double gettimeofday_sec()
{
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return tv.tv_sec + (double)tv.tv_usec*1e-6;
}

int compression(string input_file, string output_file, uint64_t k) {
  ifstream ifs(input_file.c_str());
  ofstream ofs(output_file.c_str());
  PACBEEP pac;
  uint64_t size = 0;
  pac.Init(k*1024*1024);
  for (vector<uint8_t> buf(10000); !ifs.eof();) {
    ifs.read((char*)&buf[0], sizeof(buf[0])*10000);
    for (vector<uint8_t>::iterator it = buf.begin();
	 it != buf.end() && *it; ++it) {
      pac.InsertChar(*it, ofs);
    }
    size += buf.size();
    cerr << "\rsize = " << size << " (bytes), #rules = " << pac.NumRule() << flush;
    fill_n(buf.begin(), 10000, 0);
  }
  pac.Flush(ofs);
  cerr << "\rsize = " << size << " (bytes), #rules = " << pac.NumRule() << endl;
  ifs.close(); ofs.close();
  return 1;
}

int decompression(const string& input_file, const string& output_file) {
  ifstream ifs(input_file.c_str());
  ofstream ofs(output_file.c_str());

  slp2txt(ifs, ofs);
  ifs.close();
  ofs.close();
  return 1;
}

int main(int argc, char* argv[]) {
  cmdline::parser p;
  p.add<string>("mode",       'm', "mode", true, "compress");
  p.add<string>("input_file", 'i', "input file", true);
  p.add<string>("output_file",'o', "output file", true);
  p.add<uint32_t>("bucket_width", 'w', "bucket width [w*10^6]", false, 100);
  p.set_program_name("pacbeep");

  if (!p.parse(argc, argv)) {
    cerr << p.usage() << endl;
    return -1;
  }

  string mode = p.get<string>("mode");
  if (mode == "compress") {
    return compression(p.get<string>("input_file"), 
		       p.get<string>("output_file"),
		       p.get<uint32_t>("bucket_width"));
  }
  else if (mode == "decompress") {
    return decompression(p.get<string>("input_file"),
			 p.get<string>("output_file"));
  }
  else {
    p.usage();
  }

  return 0;
}
